package cn.calm.repaymentNotice.client;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import cn.calm.repaymentNotice.R;
import cn.calm.repaymentNotice.adapter.RepaymentNoticeAdapter;
import cn.calm.repaymentNotice.dao.DBService;
import cn.calm.repaymentNotice.entity.CreditCardRecord;
import cn.calm.repaymentNotice.entity.CreditPlanRecord;
import cn.calm.repaymentNotice.entity.RepaymentNotice;
import cn.calm.repaymentNotice.entity.RepaymentNoticeInfo;
import cn.calm.repaymentNotice.service.RepaymentNoticeService;
import cn.calm.repaymentNotice.util.DateUtil;

public class MainActivity extends Activity {

	private static String TAG = "repaymentNotice.client";
	private List<RepaymentNoticeInfo> list;
	private Dialog infoDialog;
	private DBService dao ;
	public static final int DIALOG_CREDIT_CARD = 0;
	public static final int DIALOG_CREDIT_PLAN = 1;
	public static final int DIALOG_WAIT_INFO = 2;
	public static final int DIALOG_CREDIT_CONF = 3;
	public static final int DIALOG_CREDIT_CONF_DELETE = 4;
	private RepaymentNoticeInfo info;
	private	RepaymentNoticeAdapter noticeAdapter;
	/**
	 * Called when the activity is first created.
	 * 
	 * @param savedInstanceState
	 *            If the activity is being re-initialized after previously being
	 *            shut down then this Bundle contains the data it most recently
	 *            supplied in onSaveInstanceState(Bundle). <b>Note: Otherwise it
	 *            is null.</b>
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate");
		try {
			list = getDbService().listAll();
			if (list.size() == 0) {
				setContentView(R.layout.main);
			} else {
				setContentView(R.layout.main_list);
				noticeAdapter = new RepaymentNoticeAdapter(
						list, this, R.layout.repayment_notice_item);

				ListView noticeList = (ListView) findViewById(R.id.noticeList);
				noticeList.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> parent,
							View view, int position, long id) {
						info=list.get(position);
						if(info.noticeType == RepaymentNotice.TYPE_CREDIT_CARD){
							showDialog(DIALOG_CREDIT_CARD);
						}else{
							showDialog(DIALOG_CREDIT_PLAN);
						}
					}
				});
				noticeList.setOnItemLongClickListener(new OnItemLongClickListener() {

					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						info=list.get(position);
						showDialog(DIALOG_CREDIT_CONF);
						return true;
					}
				});
				noticeList.setAdapter(noticeAdapter);
			}
		} catch (RepaymentNoticeException e) {
			Toast.makeText(getApplicationContext(),e.getMessage(),
					Toast.LENGTH_LONG).show();
		}
		Intent service=new Intent(this,RepaymentNoticeService.class);
		startService(service);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mflater = new MenuInflater(this);
		mflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getOrder();
		switch (id) {
		case 1:
			Intent intent = new Intent();
			intent.setClass(this, EditNoticeActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		Builder builder;
		builder=new Builder(this);
		switch (id) {
		case DIALOG_CREDIT_CARD:
			//创建还款对话框
			builder.setMessage(String.format("你确定已经您的信用卡[%s]已经还款?",info.name));
			builder.setCancelable(false);
			builder.setPositiveButton("确定已经还款", new OnClickListener() {
			
				public void onClick(DialogInterface dialog, int which) {
					long days=DateUtil.subDays(info.predictRepaymentDate);
					if(info.preNoticeDays < days){
						showDialog(DIALOG_WAIT_INFO);
					}else{
						try {
							CreditCardRecord rec=getDbService().getCreditCardRecord(info);
							rec.repaymentDate=new Date();
							rec.result=1;
							Calendar today=Calendar.getInstance();
							today.setTimeInMillis(info.predictRepaymentDate.getTime());
							today.add(Calendar.MONTH, 1);
							getDbService().updateCreditCardRecord(rec);
							rec=new CreditCardRecord();
							rec.repaymentNoticeId=info.id;
							rec.predictRepaymentDate=today.getTime();
							getDbService().saveCreditCardRecord(rec, null);
							refreshui();
						} catch (RepaymentNoticeException e) {
							Toast.makeText(getApplicationContext(),e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					}
				}

			});
			builder.setNegativeButton("不,还不确定", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					if(infoDialog!=null){
						infoDialog.dismiss();
					}
				}
			});
			infoDialog=builder.create();
			return infoDialog;
		case DIALOG_WAIT_INFO:
			//创建提醒对话框
			builder.setMessage("到还款日还早呢!过一段时间再还款!");
			builder.setCancelable(false);
			builder.setPositiveButton("确定", new OnClickListener() {
			
				public void onClick(DialogInterface dialog, int which) {
					infoDialog.dismiss();
				}
			});
			infoDialog=builder.create();
			return infoDialog;
		case DIALOG_CREDIT_PLAN:
			//创建还款对话框
			builder.setMessage(String.format("你确定已经您的信用卡[%s]已经还款?",info.name));
			builder.setCancelable(false);
			builder.setPositiveButton("确定已经还款", new OnClickListener() {
			
				public void onClick(DialogInterface dialog, int which) {
					long days=DateUtil.subDays(info.predictRepaymentDate);
					if(info.preNoticeDays < days){
						showDialog(DIALOG_WAIT_INFO);
					}else{
						try {
							CreditPlanRecord rec=getDbService().getCreditPlanRecord(info);
							rec.repaymentDate=new Date();
							rec.result=1;
							Calendar today=Calendar.getInstance();
							today.setTimeInMillis(info.predictRepaymentDate.getTime());
							today.add(Calendar.MONTH, 1);
							getDbService().creditPlanRepayment(rec);
							refreshui();
						} catch (RepaymentNoticeException e) {
							Toast.makeText(getApplicationContext(),e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					}
				}
			});
			builder.setNegativeButton("不,还不确定", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					if(infoDialog!=null){
						infoDialog.dismiss();
					}
				}
			});
			infoDialog=builder.create();
			return infoDialog;
		case DIALOG_CREDIT_CONF:
			//创建还款对话框
			builder.setMessage("你想做点什么啊");
			builder.setCancelable(false);
			builder.setPositiveButton("删除", new OnClickListener() {
			
				public void onClick(DialogInterface dialog, int which) {
					showDialog(DIALOG_CREDIT_CONF_DELETE);
				}
			});
			builder.setNeutralButton("修改", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent=new Intent();
					intent.putExtra("notice_id", info.id);
					intent.setClass(MainActivity.this, EditNoticeActivity.class);
					startActivity(intent);
				}
			});
			builder.setNegativeButton("哦,点错了", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					if(infoDialog!=null){
						infoDialog.dismiss();
					}
				}
			});
			infoDialog=builder.create();
			return infoDialog;
		case DIALOG_CREDIT_CONF_DELETE:
			//创建还款对话框
			String message;
			if(info.noticeType==RepaymentNotice.TYPE_CREDIT_CARD){
				message="你确定删除信用卡[%s]的提醒?";
			}else{
				message="你确定删除贷款[%s]的提醒?";
			}
			builder.setMessage(String.format(message,info.name));
			builder.setCancelable(false);
			builder.setPositiveButton("删除", new OnClickListener() {
			
				public void onClick(DialogInterface dialog, int which) {
					try {
						getDbService().deleteRepaymentNotice(info);
						refreshui();
						Toast.makeText(getApplicationContext(),"恭喜你删除成功",
								Toast.LENGTH_LONG).show();
					} catch (RepaymentNoticeException e) {
						Toast.makeText(getApplicationContext(),e.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				}
			});
			builder.setNegativeButton("点错了", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					if(infoDialog!=null){
						infoDialog.dismiss();
					}
				}
			});
			infoDialog=builder.create();
			return infoDialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
	private void refreshui() throws RepaymentNoticeException {
		list.clear();
		list.addAll(getDbService().listAll());
		if(list.size()>0){
			noticeAdapter.notifyDataSetChanged();
		}else{
			Intent intent=new Intent();
			intent.setClass(MainActivity.this, MainActivity.class);
			startActivity(intent);
		}
	}
	/**
	 * 获得数据库操作服务
	 * @return
	 */
	private DBService getDbService() {
		if(dao==null){
			dao = DBService.getInstance(getApplicationContext());
		}
		return dao;
	}
}
